﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Threading;

namespace Infrastructure.WpfClient.Composite.Regions.TabRegion
{
    public class AnimatedTabControl : TabControl
    {
        public AnimatedTabControl()
        {
            DefaultStyleKey = typeof(AnimatedTabControl);    
        }
        public static readonly RoutedEvent SelectionChangingEvent = EventManager.RegisterRoutedEvent("SelectionChanging", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(AnimatedTabControl));

        private DispatcherTimer timer;
        private SelectionChangedEventArgs lastArgs;

      

        public event RoutedEventHandler SelectionChanging
        {
            add { AddHandler(SelectionChangingEvent, value); }
            remove { RemoveHandler(SelectionChangingEvent, value); }
        }

        protected override void OnSelectionChanged(SelectionChangedEventArgs e)
        {
            if (this.Items.Count == 1)
            {
                base.OnSelectionChanged(e);
            }
            else if (e.RemovedItems.Count > 0 )
            {
                this.RaiseSelectionChangingEvent();

                this.StopTimer();
                this.lastArgs = e;

                this.timer = new DispatcherTimer
                {
                    Interval = new TimeSpan(0, 0, 0, 0, 500)
                };
                this.timer.Tick += this.Timer_Tick;
                this.timer.Start();
            }
            
        }

        //// This method raises the Tap event
        private void RaiseSelectionChangingEvent()
        {
            var args = new RoutedEventArgs(SelectionChangingEvent);
            RaiseEvent(args);
        }

        private void StopTimer()
        {
            if (this.timer != null)
            {
                this.timer.Stop();
                this.timer = null;
            }
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            this.StopTimer();
            base.OnSelectionChanged(this.lastArgs);
        }
    }
}
